
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser')

var app = express();
// 引用中间件
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// 设置静态资源
app.use(express.static('public'));
// 静态数据
var db = require('./data/db');
// 设置模板路径及类型
app.set('views', './views');
app.set('view engine', 'ejs');

// 首页
app.get('/', (req, res) => {
	if(req.cookies.userNamer){
		res.render('index', {'status':req.cookies.userNamer, 'db':db});
	}else{
		res.render('index', {'status':false, 'db':db});
	}
});


// 留言板路由

app.post('/submsg', (req, res) => {
	var msg = req.body;
	if(req.cookies.userNamer){
		res.render('submsg', {'status':req.cookies.userNamer, msg});
	}else{
		res.render('submsg', {'status':false, msg});
	}
	
});

// 内容页路由
app.get('/list/:id' ,(req, res) => {
	var data = getArticle(req.params.id);
	if(req.cookies.userNamer){
		res.render('article', { 'status':req.cookies.userNamer, data });
	}else{
		res.render('article', {'status':false, data});
	}
	
});

// 获取内容数据
function getArticle(id){
	for(var i=0; i<db.length; i++){
		if(db[i]['aid'] == id){
			return db[i];
		}
	}
}

// 内容列表
app.get('/list', (req, res) => {
	if(req.cookies.userNamer){
		res.render('list', { 'status':req.cookies.userNamer, db });
	}else{
		res.render('list', {'status':false, db});
	}
});

// 登录
var uName = null;
app.get('/login', (req, res) => {
	res.render('login', {'status':false});
});
app.post('/login', (req, res) => {
	if(req.body.user == 'admin' && req.body.password == 'admin'){
		res.cookie('userNamer', req.body.user,{'path': '/'});
		res.redirect('/');
	}else{
		res.render('login', {'status':false});
	}
});
// 注销
app.get('/logout', (req, res) => {
	res.clearCookie('userNamer');
	res.redirect('/');
});
// 注册
app.get('/register', (req, res) => {
	res.render('register', {'status':false});
});	

app.post('/register', (req, res) => {
	res.redirect('/login');
});	

// 关于我们
app.get('/about', (req, res) => {
	if(req.cookies.userNamer){
		res.render('about', { 'status':req.cookies.userNamer });
	}else{
		res.render('about', {'status':false});
	}
});

app.listen(3000, () => {
	console.log('server runing listen 3000');
});